package handler;

import bean.User;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import service.UserService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class Cancel implements Controller {
    private UserService service;

    public void setService(UserService service) {
        this.service = service;
    }

    @Override
    public ModelAndView handleRequest(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        ModelAndView modelAndView = new ModelAndView("cancel");
        HttpSession session = req.getSession();
        String userName = (String) session.getAttribute("user-name");
        if (req.getMethod().equals("POST")) {
            String password = req.getParameter("password");
            if (User.verifyPassword(password)) {
                User user = new User(userName, password);
                int userId = service.verify(user);
                if (userId > 0) {
                    boolean state = service.cancel(userId);
                    if (state) {
                        modelAndView.setViewName("redirect:logout");
                    } else {
                        modelAndView.addObject("error", "注销失败，未知错误");
                    }
                } else {
                    modelAndView.addObject("error", "注销失败，密码错误");
                }
            } else {
                modelAndView.addObject("error", "密码的长度不符合规范");
            }
        }
        return modelAndView;
    }
}
